package com.jiulan.hearthearing.http;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.widget.Toast;

import com.jiulan.hearthearing.base.BaseModel;
import com.jiulan.hearthearing.common.MethodUtils;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.ui.login.activity.LoginVerificationCodeActivity;
import com.jiulan.hearthearing.utils.JsonUtils;
import com.jiulan.hearthearing.utils.LogUtils;
import com.jiulan.hearthearing.utils.StringUtils;
import com.jiulan.hearthearing.widget.LoadingDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;

import org.json.JSONObject;

import java.io.File;
import java.net.SocketTimeoutException;
import java.net.UnknownServiceException;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    private Context context;

    public HttpRequest(Context context) {
        this.context = context;
    }

    private String format(String url) {
        return UrlConstants.Base_Http + url;
    }

    private HttpHeaders getHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Authori-zation", "Bearer " + MethodUtils.getToken(context));
        return httpHeaders;
    }

    private HttpHeaders getHeaders1() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Authori-zation", "Bearer " + MethodUtils.getToken(context));
        httpHeaders.put("Content-Type", "multipart/form-data");
        return httpHeaders;
    }

    public static boolean isValidContext(Context c) {
        Activity a = (Activity) c;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (a.isDestroyed() || a.isFinishing()) {
                return false;
            } else {
                return true;
            }
        } else if (a.isFinishing()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 返回状态判断
     *
     * @param obj
     */
    private void checkStatus(Object obj) {
        if (obj instanceof BaseModel){
            BaseModel model = (BaseModel) obj;
            if (model.getStatus() == 400) {
                Toast.makeText(context, model.getMsg(), Toast.LENGTH_SHORT).show();
            }
            if (model.getStatus() == 41000) {
                LoginVerificationCodeActivity.actionStart(context, "");
            }
        }
    }

    /**
     * 返回错误提示
     *
     * @param response
     */
    private void checkThrowable(com.lzy.okgo.model.Response<String> response) {
        Throwable throwable = response.getException();
        LogUtils.e("error", throwable.toString());
        if (throwable instanceof SocketTimeoutException) {
            Toast.makeText(context, "连接超时,请检查网络", Toast.LENGTH_SHORT).show();
        } else if (throwable instanceof UnknownServiceException) {
            Toast.makeText(context, "未找到服务器,请检查网络", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "接口异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 执行普通的get请求
     *
     * @param url
     * @param loadingMsg
     * @param params
     * @param clazz
     * @param mCallBack
     * @param <T>
     */

    public <T> void doGet(final String url, String loadingMsg, final Map params, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", format(url));
        final LoadingDialog finalDialog = dialog;
        try {
            OkGo.<String>get(format(url)).tag(this).params(params).headers(getHeaders()).execute(new StringCallback() {
                @Override
                public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    String body = response.body();
                    LogUtils.e(url, params.toString());
                    LogUtils.e(url, body);
                    Object obj = JsonUtils.fromJson(body, clazz);
                    if (obj != null) {
                        mCallBack.onSuccess(obj);
                        checkStatus(obj);
                    }
                }

                @Override
                public void onError(com.lzy.okgo.model.Response<String> response) {
                    super.onError(response);
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    checkThrowable(response);
                    mCallBack.onFailure(1, "接口异常" + response.code());
                }
            });
        } catch (Exception e) {
            if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                finalDialog.dismiss();
            }
            mCallBack.onFailure(-101, "接口异常");
            e.printStackTrace();
        }
    }

    public void doGet(final String url, String loadingMsg, Map params, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", format(url));
        final LoadingDialog finalDialog = dialog;
        try {
            OkGo.<String>get(format(url)).tag(this).params(params).headers(getHeaders()).execute(new StringCallback() {
                @Override
                public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    String body = response.body();
                    LogUtils.e(url, body);
                    Object obj = JsonUtils.fromJson(body, BaseModel.class);
                    if (obj != null) {
                        mCallBack.onSuccess(obj);
                    }
                }

                @Override
                public void onError(com.lzy.okgo.model.Response<String> response) {
                    super.onError(response);
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    checkThrowable(response);
                    mCallBack.onFailure(1, "接口异常" + response.code());
                }
            });
        } catch (Exception e) {
            if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                finalDialog.dismiss();
            }
            mCallBack.onFailure(-101, "接口异常");
            e.printStackTrace();
        }
    }

    public <T> void doGet(final String url, String loadingMsg, HttpParams params, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", format(url));
        final LoadingDialog finalDialog = dialog;
        try {
            OkGo.<String>get(format(url)).tag(this).params(params).headers(getHeaders()).execute(new StringCallback() {
                @Override
                public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    String body = response.body();
                    LogUtils.e(url, body);
                    Object obj = JsonUtils.fromJson(body, clazz);
                    if (obj != null) {
                        mCallBack.onSuccess(obj);
                        checkStatus(obj);
                    }
                }

                @Override
                public void onError(com.lzy.okgo.model.Response<String> response) {
                    super.onError(response);
                    if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                        finalDialog.dismiss();
                    }
                    checkThrowable(response);
                    mCallBack.onFailure(1, "接口异常" + response.code());
                }
            });
        } catch (Exception e) {
            if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                finalDialog.dismiss();
            }
            mCallBack.onFailure(-101, "接口异常");
            e.printStackTrace();
        }
    }

    /**
     * 执行普通的post请求
     *
     * @param url
     * @param params
     * @param clazz
     * @param mCallBack
     * @param <T>
     */

    public <T> void doPost(final String url, String loadingMsg, Map params, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", JsonUtils.mapToJson(params));
        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).params(params).headers(getHeaders()).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, clazz);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                    checkStatus(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                LogUtils.e("response", response.getException().getMessage());
                mCallBack.onFailure(1, "接口异常");
            }
        });

    }

    /**
     * post 返回实体类是BaseModel类型
     *
     * @param url
     * @param loadingMsg
     * @param params
     * @param mCallBack
     */
    public void doPost(final String url, String loadingMsg, Map params, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", params.toString());
        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).params(params).headers(getHeaders()).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, BaseModel.class);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                mCallBack.onFailure(1, "接口异常" + response.code());
            }
        });

    }

    /**
     * 执行普通的post请求
     *
     * @param url
     * @param params
     * @param clazz
     * @param mCallBack
     * @param <T>
     */
    public <T> void doPost(final String url, String loadingMsg, JSONObject params, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        LogUtils.e("json", params.toString());
        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).upJson(params.toString()).headers(getHeaders()).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, clazz);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                    checkStatus(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                mCallBack.onFailure(1, "接口异常" + response.code());
            }
        });

    }

    public void doPost(final String url, String loadingMsg, JSONObject params, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).upJson(params.toString()).headers(getHeaders()).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, BaseModel.class);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                mCallBack.onFailure(1, "接口异常" + response.code());
            }
        });

    }

    /**
     * 执行普通的文件下载请求
     *
     * @param path      文件保存路径
     * @param name      文件名称
     * @param url       文件下载地址
     * @param mCallBack 回调结果
     */
    public void doDownloadFile(String path, String name, String url, final HttpFileCallBack mCallBack) {
        try {
            OkGo.<File>get(format(url)).tag(this).execute(new FileCallback() {
                @Override
                public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                    File body = response.body();
                    mCallBack.onSuccess(body);
                }

                @Override
                public void downloadProgress(Progress progress) {
                    /**
                     *@param fraction       下载的进度，0-1
                     *@param totalSize      总字节长度, byte
                     *@param currentSize    本次下载的大小, byte
                     *@param speed;         网速，byte/s
                     */
                    mCallBack.inProgress(progress.currentSize, progress.totalSize, progress.fraction, progress.speed);
                }

                @Override
                public void onError(com.lzy.okgo.model.Response<File> response) {
                    super.onError(response);

                }
            });

        } catch (Exception e) {
            mCallBack.onError(e);
            e.printStackTrace();
        }
    }

    /**
     * 上传文件 单个文件上传
     *
     * @param url
     * @param loadingMsg
     * @param key        单个文件上传的key
     * @param file       单个文件
     * @param mCallBack
     */
    public <T> void doUploadFile(final String url, String loadingMsg, String key, File file, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));
        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).headers(getHeaders()).params(key, file).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, clazz);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                    checkStatus(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                mCallBack.onFailure(1, "接口异常" + response.code());
            }
        });

    }

    /**
     * 上传文件 一个key上传多个文件
     *
     * @param url
     * @param loadingMsg
     * @param key
     * @param files
     * @param mCallBack
     */
    public <T> void doUploadFile(final String url, String loadingMsg, Map params, String key, List<File> files, final Class<T> clazz, final HttpStringCallBack mCallBack) {
        LoadingDialog dialog = null;
        if (loadingMsg != null && context instanceof Activity && isValidContext(context)) {
            dialog = new LoadingDialog(context, loadingMsg);
            dialog.show();
        }
        LogUtils.e("token", MethodUtils.getToken(context));

        final LoadingDialog finalDialog = dialog;
        OkGo.<String>post(format(url)).tag(this).isMultipart(true).headers(getHeaders1()).params(params).addFileParams(key, files).execute(new StringCallback() {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                String body = response.body();
                LogUtils.e(url, body);
                Object obj = JsonUtils.fromJson(body, clazz);
                if (obj != null) {
                    mCallBack.onSuccess(obj);
                    checkStatus(obj);
                }
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<String> response) {
                super.onError(response);
                if (finalDialog != null && context instanceof Activity && isValidContext(context)) {
                    finalDialog.dismiss();
                }
                checkThrowable(response);
                mCallBack.onFailure(1, "接口异常" + response.code());
            }
        });

    }
}
